package com.xd.core.api.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xd.common.base.CustomRowHeightColWidthHandler;
import com.xd.common.base.RowHeightColWidthModel;
import com.xd.common.constant.SysConstant;
import com.xd.common.util.SecurityUtil;
import com.xd.core.api.entity.AdvancePaymentOrder;
import com.xd.core.api.mapper.AdvancePaymentOrderMapper;
import com.xd.core.api.service.IAdvancePaymentOrderService;
import com.xd.core.finance.dto.AdvancePaymentRecordDto;
import com.xd.core.finance.vo.AdvancePaymentRecordVo;
import com.xd.core.mission.entity.MissionCenterInfo;
import com.xd.core.mission.mapper.MissionCenterInfoMapper;
import com.xd.core.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 预付款订单信息表 服务实现类
 * </p>
 *
 * @author ZX
 * @since 2025-06-27
 */
@Service
public class AdvancePaymentOrderServiceImpl extends ServiceImpl<AdvancePaymentOrderMapper, AdvancePaymentOrder> implements IAdvancePaymentOrderService {

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private AdvancePaymentOrderMapper repaymentOrderInfoMapper;
    @Autowired
    private MissionCenterInfoMapper missionCenterInfoMapper;
    @Value("${image.localPathDir}")
    private String localPathDir;
    @Value("${image.exportFile}")
    private String exportFile;

    /***
     * @description 预付款记录
     * @author Zch
     * @date 11:29 2025/7/16 星期三
     * @return com.github.pagehelper.Page<com.xd.core.finance.vo.AdvancePaymentRecordVo>
     **/
    @Override
    public Page<AdvancePaymentRecordVo> getAdvancePaymentRecord(AdvancePaymentRecordDto dto) {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        Integer companyId = null;
        List<Integer> userIds = null;
        if (companyType.equals(SysConstant.USER_COMPANY_TYPE_ONE) || companyType.equals(SysConstant.USER_COMPANY_TYPE_FOUR)) {
            companyId = dto.getCompanyId();
        } else if (companyType.equals(SysConstant.USER_COMPANY_TYPE_TOW)) {
            companyId = SecurityUtil.getLoginCompanyId();
            userIds = iSysUserService.getUserIdsByGroup();
        } else if (companyType.equals(SysConstant.USER_COMPANY_TYPE_THREE)) {//代理
            return null;
        }
        //开始分页
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return repaymentOrderInfoMapper.getAdvancePaymentRecord(dto, companyId, userIds);
    }

    /***
     * @description 预付款记录导出
     * @author Zch
     * @date 14:19 2025/7/16 星期三
     * @return void
     **/
    @Override
    public void exportAdvancePaymentRecord(AdvancePaymentRecordDto dto, Integer id) {
        String name = "";
        if ("1".equals(dto.getPayPass())) {
            name = "通道一预付款记录excel文件" + UUID.randomUUID().toString().replace("-", "");
        } else {
            name = "官方通道（标准）预付款记录excel文件" + UUID.randomUUID().toString().replace("-", "");
        }
        Integer companyId = SecurityUtil.getLoginCompanyId();
        FileOutputStream fileOutputStream = null;
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setId(id);
        missionCenterInfo.setFileName(name + ".xlsx");
        String filePath = localPathDir + exportFile + "/" + companyId;
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        try {
            List<RowHeightColWidthModel> rowHeightColWidthList = new ArrayList<>();
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 0, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 1, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 2, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 3, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 4, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 5, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 6, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 7, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 8, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 9, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 10, 20));
            File file = new File(filePath + "/" + name + ".xlsx");
            fileOutputStream = new FileOutputStream(file);

            ExcelWriter write = EasyExcel.write(fileOutputStream, AdvancePaymentRecordVo.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(name).registerWriteHandler(new CustomRowHeightColWidthHandler(rowHeightColWidthList)).build();
            dto.setPageSize(0);
            List<AdvancePaymentRecordVo> list = getAdvancePaymentRecord(dto);
            write.write(list, writeSheet);
            write.finish();
            fileOutputStream.flush();
            //修改文件状态 导出成功
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_TOW);
            missionCenterInfo.setFileUrl(exportFile + "/" + companyId + "/" + name + ".xlsx");
            missionCenterInfoMapper.updateById(missionCenterInfo);
        } catch (Exception e) {
            //修改文件状态 导出失败
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_THREE);
            missionCenterInfoMapper.updateById(missionCenterInfo);
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
